/*
 * LengthValidator.java
 * 
 * Created on 21-Aug-2007, 08:36:45
 * 
 * Copyright (C)
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

package com.grubby.databean.constraints.validation;

import com.grubby.databean.constraints.annotation.Length;
import java.lang.annotation.Annotation;

/**
 * A validator for the {@link Length Length} constraint.
 * @see Length
 *
 * @author A. HARMEL-LAW. 
 * E: andrew.harmel.law@gmail.com
 * @version 0.1
 */
public class LengthValidator extends AbstractConstraintValidator {
    
    /**
     * Constructs a LengthValidator object.
     */
    // suppress the unchecked warning for unchecked generic array creation
    @SuppressWarnings("unchecked")
    public LengthValidator() {
        super(Length.class);
    }

    public ConstraintViolation validate(Object objValue, Annotation constraint) {

        ensureConstraintIsSupported(constraint);

        Length l = (Length)constraint;
        ConstraintViolation result = null;

        String value = (objValue != null ? objValue.toString() : null);
        
        if (value == null) {
            result = new ConstraintViolation(l,
                "Length constraint violated. The length provided was null.");
        } else if (value.length() != l.value()) {
            result = new ConstraintViolation(l,
                "Length constraint violated. Length provided (" + value.length() + 
                ") is not that the @Length annotation allows (" + l.value() + ")");
        }

        return result;
    }
    
}
